export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    try {
      // 获取客户端 IP 并进行匿名化哈希处理
      const ip = request.headers.get('CF-Connecting-IP') || 'unknown';
      const ipHash = await hashIP(ip);
      
      // 更新或创建访问记录
      const result = await env.DB.prepare(
        `INSERT INTO ip_logs (ip_hash, last_vist_time, vist_count)
         VALUES (?1, ?2, 1)
         ON CONFLICT(ip_hash) DO UPDATE SET
           last_vist_time = ?2,
           vist_count = vist_count + 1
         RETURNING last_vist_time, vist_count;`
      )
        .bind(ipHash, new Date().toISOString())
        .first<{ last_vist_time: string; vist_count: number }>();

      // 处理查询结果
      if (!result) {
        throw new Error('Database operation failed');
      }

      // 构建响应页面
      return new Response(`
        <!DOCTYPE html>
        <html>
        <head>
          <title>访问记录</title>
          <meta charset="UTF-8">
          <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; padding: 20px; }
            .container { max-width: 600px; margin: 0 auto; }
            .info { background: #f4f4f4; padding: 20px; border-radius: 8px; }
          </style>
        </head>
        <body>
          <div class="container">
            <h1>访问信息</h1>
            <div class="info">
              <p><strong>上次访问时间:</strong> ${formatDateTime(result.last_vist_time)}</p>
              <p><strong>总访问次数:</strong> ${result.vist_count}</p>
            </div>
            <p><small>注：您的 IP 地址已进行匿名哈希处理，不会存储原始地址</small></p>
          </div>
        </body>
        </html>
      `, {
        headers: { 'Content-Type': 'text/html; charset=UTF-8' }
      });

    } catch (err) {
      // 错误处理
      return new Response(`错误: ${err.message}`, { status: 500 });
    }
  }
};

// 类型定义
export interface Env {
  DB: D1Database;
}

// IP 哈希函数 (SHA-256)
async function hashIP(ip: string): Promise<string> {
  const encoder = new TextEncoder();
  const data = encoder.encode(ip);
  const hashBuffer = await crypto.subtle.digest('SHA-256', data);
  
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}

// 日期时间格式化函数
function formatDateTime(isoString: string): string {
  const date = new Date(isoString);
  return new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    timeZoneName: 'short'
  }).format(date);
}